<template>
  <cu-layout :navProp="{ title: roomType, bgColor: 'rgba(255,255,255)', placeholder: true }">
    <view :class="[`${prefixCls}-house-list`]">
      <uv-sticky offsetTop="0" :customNavHeight="$Platform.navbar" :class="isSticky ? '' : 'isSticky'">
        <view class="navbar-height"></view>
        <view class="input-box">
          <uv-input prefixIcon="search" prefixIconStyle="font-size: 22px;color: #909399" placeholder="小区/商圈/地铁站/地标" shape="circle" v-model="number" @blur="bindKeyInput">
            <template v-slot:prefix>
              <view class="current-location">
                <uv-text
                  suffixIcon="arrow-down-fill"
                  size="14px"
                  lines="1"
                  iconStyle="top:1px; font-size:12px; line-height:12px;margin:0 8px"
                  :text="cityConfig.cityName || '定位中'"
                  :customStyle="{ width: '30px' }"
                  @click="onClickLocation"
                />
              </view>
            </template>
          </uv-input>
        </view>
        <search-list @scroll="scroll" @emit-change-data="handleChangeSearch" @emit-change-icon="changeIconStatus" :list="list" :isNomore="this.projectPages.status"></search-list>
        <!-- 标签 -->
        <scroll-view v-if="search_tag_list.length && isScroll" class="scroll-view" scroll-x="true">
          <view class="tag-list">
            <view
              v-for="(item, index) in search_tag_list"
              :key="index"
              :class="[tabActiveList.includes(item.tag_value) ? 'tag-active' : 'tag-item', 'tag-item']"
              @click="handleChangeTag(item.tag_value)"
            >
              {{ item.tag_key }}
            </view>
          </view>
        </scroll-view>
      </uv-sticky>
      <view class="housing-resources">
        <template v-if="projectPages.dataList.length == 0">
          <cu-empty mode="data" :text="projectPages.status == 'loading' ? '正在加载' : '没有合适房源'"> </cu-empty>
        </template>
        <template v-else>
          <view class="unit-type-card" v-for="(item, index) in projectPages.dataList" :key="index" @click="handleDetail(item)">
            <view class="left">
              <image :src="item.cover" alt="" />
              <image class="icon" src="https://szct-oss.boyuplus.com/mp/mini/room/has-video.png" alt="" />
            </view>
            <view class="right">
              <view class="roomTypeTitle">{{ item.type + '·' + item.project_name + ' ' + item.room_type_name }}</view>
              <view class="detail">{{ item.jz_area + 'm² | ' + item.house_orientation }}</view>
              <view class="address-text">
                <uv-icon name="map-fill" color="#ccc" size="14"></uv-icon>
                <text class=".uv-line-1">{{ item.subway_info }}</text>
              </view>
              <view class="tags">
                <view v-for="(items, indexs) in item.tag" :key="indexs"> {{ items }}</view>
              </view>
              <view class="showPrice">{{ item.old_rent }}<text>/月</text> </view>
            </view>
          </view>
          <uv-load-more :status="projectPages.status" :dashed="true" :line="true" marginTop="20px" />
        </template>
      </view>
    </view>
  </cu-layout>
</template>

<script>
import { getFilterTags, projectTop } from '@/api/home'
import share from '@/mixins/share'
import { mapGetters } from 'vuex'
import { getRoomList } from './api'
import searchList from './components/search-list'
const roomTypeObj = {
  0: '新开业',
  1: '地铁房',
  2: '精选整租',
  3: '单身公寓',
}
export default {
  name: 'house',
  mixins: [share],
  components: { searchList },
  data() {
    return {
      pageDataInitFinished: false,
      opacityVal: 0,
      isSticky: false,
      searchkeyword: '',
      onShareAppMessage: {
        title: '',
        path: '',
      },
      isScroll: true,
      list: [
        { title: '全部区域', key: 'business_district', options: [], value: {}, icon: 1 },
        { title: '离我最近', key: 'rate', icon: 0, value: '' },
        { title: '价格排序', key: 'price', icon: 0, value: '' },
        { title: '房源筛选', key: 'districts', options: [], value: [], icon: 1 },
      ],
      search_tag_list: [], // 商圈标签
      tabActiveList: [],
      projectPages: {
        status: 'nomore',
        tags: [],
        latitude: '',
        longitude: '',
        orderBy: '',
        // minPrice: '',
        // orderBy: 'showMinPrice:asc',
        business_district: '',
        districts: '',
        page: 1,
        length: 10,
        dataList: [],
      },
      roomType: '',
      number: '',
    }
  },
  watch: {
    'cityConfig.cityId'(nv) {
      this.getData()
    },
  },
  // 计算属性
  computed: {
    ...mapGetters(['cityConfig', 'locationInfo']),
  },
  filters: {},
  onLoad(options) {
    this.roomType = roomTypeObj[options.type]
    //设置顶部标题
    uni.setNavigationBarTitle({
      title: this.roomType,
    })
    this.getData()
  },
  onReady() {
    // 获取下定位栏的高度
    setTimeout(() => {
      uni
        .createSelectorQuery()
        .select('.navbar-height')
        .boundingClientRect((res) => {
          this.scrollTop = res.top - this.$Platform.navbar
        })
        .exec()
    }, 500)
  },
  onShow() {},
  onHide() {},
  // 下拉刷新
  onPullDownRefresh() {},
  // 加载更多
  onReachBottom() {
    if (this.projectPages.total != this.projectPages.dataList.length) {
      this.projectPages.page++
      // 获取项目数据
      this.projectList()
    }
  },
  // 页面滚动
  onPageScroll(e) {
    let top = e.scrollTop
    this.isSticky = top > 65
    this.opacityVal = top > this.$Platform.navbar ? 1 : top * 0.01
  },
  options: {
    styleIsolation: 'shared',
  },
  methods: {
    bindKeyInput(value) {
      this.getData()
    },
    // 操作左侧定位
    onClickLocation() {
      this.$ROUTE.go('/pages/subpackage/city/index')
      this.$emit('clickLocation')
    },
    handleDetail(item) {
      this.$ROUTE.go('/pages/subpackage/housing-resources/room-detail/index', { room_id: '', roomTypeId: item.room_type_id, projectId: item.project_id })
    },
    // 获取页面数据
    async getData() {
      this.projectPages.page = 1
      this.projectPages.dataList = []
      this.getFilterTags()
      this.projectList()
    },
    async getFilterTags() {
      const { cityId } = this.cityConfig
      const { data } = await getFilterTags({ cityId })
      const { filter, options, search_tag_list, priceList } = data
      this.search_tag_list = search_tag_list.sort((a, b) => {
        return a.sort - b.sort
      })
      console.log('this.search_tag_list', this.search_tag_list)

      this.list[3].options = filter.map((v) => {
        v.value = []
        return v
      })
      const ojb = {
        name: 'price',
        title: '租金预算',
        list: priceList,
        value: [],
      }
      this.list[3].options.unshift(ojb)
      this.list[0].options = options.filter((item) => {
        if (item.name === '商圈' || item.name === '地铁') {
          item.children = item.children.map((v) => {
            v.id = v.id || v.name
            v.field = v.id ? v.id : v.name
            return v
          })
        }
        return item.name != '公司'
      })
      // 过滤掉通勤找房
    },
    async projectTop() {
      const { cityId } = this.cityConfig
      const { data } = await projectTop({ cityId })
      const { search_tag_list } = data
      const list = [...this.search_tag_list, ...search_tag_list]
      let uniqueArray = list.filter((obj, index, self) => index === self.findIndex((t) => t.tag_value === obj.tag_value))
      this.search_tag_list = uniqueArray.sort((a, b) => {
        return a.sort - b.sort
      })
    },
    isChinese(str) {
      // 匹配中文字符的正则表达式
      var reg = /[\u4e00-\u9fa5]/
      return reg.test(str)
    },
    changeAreaData({ value }) {
      if (!value) return
      let map = { districts: [], business_district: [], subway: [] }
      value.forEach((v) => {
        if (this.isChinese(v.fieldKey)) {
          if (v.key && v.key.length) {
            map.business_district = [...map.business_district, ...v.key]
          } else {
            map.districts.push(v.fieldKey)
          }
        } else {
          if (v.key && v.key.length) {
            map.subway.push(v.key)
          } else {
            map.subway.push(v.fieldKey)
          }
        }
      })
      return map
    },
    async projectList() {
      const { tags, orderBy, page, length } = this.projectPages
      const { latitude, longitude } = this.locationInfo
      const { cityId } = this.cityConfig
      const areaData = this.list[0].value
      const filterData = this.list[3].value
      const areaDataValue = this.changeAreaData(areaData)
      // console.log('areaDataValue', areaDataValue)
      const params = { cityId, tags: JSON.stringify(tags), orderBy, latitude, longitude, page, limit: length }
      for (let key in areaDataValue) {
        params[key] = JSON.stringify(areaDataValue[key])
      }
      filterData.forEach((v) => {
        if (v.name === 'price') {
          const price = v.value.match(/\d+/g)
          params['minPrice'] = price[0]
          params['maxPrice'] = price[1] || 10000
        } else {
          params[v.name] = JSON.stringify(v.value)
        }
      })
      params.number = this.number
      params.type = this.roomType
      this.projectPages.status = 'loading'
      const { data } = await getRoomList(params)
      console.log(data)
      const list = data.data
      const total = data.count
      this.projectPages.total = total
      this.projectPages.dataList = [...this.projectPages.dataList, ...list]
      console.log(this.projectPages.dataList)
      if (total === this.projectPages.total) {
        this.projectPages.status = 'nomore'
      } else {
        this.projectPages.status = 'loadmore'
      }
    },
    handleJump({ type, jump_type, jump_url }) {
      if (jump_type == 'BoyuMini') {
        this.$ROUTE.go({ path: jump_url })
      } else if (jump_type == 'PageLink') {
        this.$ROUTE.go(jump_url)
      } else if (jump_type == 'Mini') {
        uni.$uv.toast('暂未开放')
      }
    },
    // 赋值选中样式
    handleChangeTag(tag_value) {
      if (this.projectPages.status == 'loading') return
      if (this.tabActiveList.includes(tag_value)) {
        this.tabActiveList.forEach((v, i) => {
          if (v == tag_value) {
            this.tabActiveList.splice(i, 1)
          }
        })
      } else {
        this.tabActiveList.push(tag_value)
      }
      this.projectPages.tags = this.tabActiveList
      this.projectPages.dataList = []
      this.projectPages.page = 1
      this.projectList()
    },
    scroll(value) {
      this.isScroll = value
      uni.pageScrollTo({
        scrollTop: this.scrollTop,
        duration: 100,
      })
    },
    handleChangeSearch({ index = '', value = false }) {
      // 距离和价格只能同时存在一种，所以特殊处理
      if (index !== '') {
        if (index === 1 || index === 2) {
          this.projectPages.orderBy = value
        } else {
          this.list[index].value = value
        }
        this.projectPages.dataList = []
        this.projectPages.page = 1
        this.projectList()
      }
    },
    changeIconStatus(index = '') {
      this.list.forEach((v) => {
        if (v.icon == 2) {
          v.icon = 1
        }
      })
      if (index !== '') {
        this.list[index].icon = 2
      }
      if (index === '') {
        this.list.forEach((v) => {
          if ((v.value && v.value.length) || v?.value?.value) {
            v.icon = 3
          }
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.#{prefixCls('house-list')} {
  position: relative;
  // $uv-primary
  .input-box {
    background: #fff;
    padding: 20rpx 32rpx;
    .input-box-style {
      width: 100%;
    }
  }
  .isSticky {
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    overflow: hidden;
  }
  .swiper-container {
    width: 100%;
    box-sizing: border-box;
    padding: 24rpx 32rpx;
    border-radius: 16rpx;
    .swiper {
      height: 128px;
      .swiper-item,
      image,
      image {
        width: 100%;
        height: 100%;
        border-radius: 16rpx;
      }
    }
  }
  .container {
    width: calc(100% - 64rpx);
    margin: 0 16px 22rpx;
    box-sizing: border-box;
    padding: 24rpx 0rpx;
    border-radius: 16rpx;
    background: #fff;
    display: flex;
    flex-wrap: wrap;

    .project-item {
      width: 25%;
      display: flex;
      align-items: center;
      flex-direction: column;
      image,
      image {
        width: 84rpx;
        height: 84rpx;
        margin-bottom: 8rpx;
      }
      text {
        font-weight: 400;
        font-size: 12px;
        color: #333333;
        line-height: 20px;
      }
    }
  }

  .scroll-view {
    background: #fff;
    padding-bottom: 12px;
  }
  .tag-list {
    width: max-content;
    min-width: 100%;
    background: #ffffff;
    display: flex;
    padding: 4px 16px;
    .tag-item {
      font-size: 12px;

      font-weight: 400;
      color: #666666;
      padding: 6px 16px;
      border: 1px solid #eeeeee;
      border-radius: 34px;
      margin-right: 8px;
    }
    .tag-active {
      color: $uv-primary;
      border-color: $uv-primary;
      background-color: #ecf5f8;
    }
  }
  .housing-resources {
    // padding-bottom: 230px; //解决高度不够状态栏无法滚动最顶部
    // margin-top: 88rpx;
    // background-image: linear-gradient(to bottom, #ffffff, #f1f2f2);
    margin-top: 20rpx;
    background-size: auto 200px;
    background-repeat: no-repeat;
    padding: 0 16rpx 40rpx;
    .housing-item {
      margin-bottom: 20rpx;
    }
  }
  .unit-type-card {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    background: #fff;
    padding: 0 10rpx;
    .left {
      width: 240rpx;
      height: 180rpx;
      background: #fff3eb;
      position: relative;
      border-radius: 16rpx;
      overflow: hidden;
      image {
        width: 100%;
        height: 100%;
      }
      .icon {
        width: 40rpx;
        height: 40rpx;
        position: absolute;
        left: 16rpx;
        top: 16rpx;
      }
    }
    .right {
      margin-left: 16rpx;
      margin-top: 8rpx;
      flex: 1;
      overflow: hidden;
      .address-text {
        display: flex;
        width: 100%;
        text {
          width: 100%;
          font-size: 22rpx;
        }
      }
      .roomTypeTitle {
        font-weight: bold;
        color: #222222;
        font-size: 28rpx;
        line-height: 40rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .detail {
        font-weight: 400;
        line-height: 32rpx;
        color: #666666;
        font-size: 22rpx;
        width: 400rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .tags {
        display: flex;
        flex-wrap: wrap;
        view {
          padding: 2rpx 8rpx;
          font-size: 22rpx;
          font-weight: 400;
          background-color: #f5f5f5;
          color: #999;
          border-radius: 8rpx;
          margin-top: 8rpx;
          margin-right: 8rpx;
        }
      }
      .showPrice {
        font-size: 32rpx;
        font-weight: bold;
        color: $uv-price-primary;
        line-height: 32rpx;
        padding-right: 4rpx;
        margin-top: 10rpx;
        text {
          margin-left: 8rpx;
          font-size: 20rpx;
          color: #999999;
        }
      }
    }
  }
}
</style>
